<!--<template>
  <div class="information_container">
    <div class="backgroundImg">
      <img
          src="../../assets/images/tushu.jpg"
          alt="背景图片"
          class="no-drag"
      />
    </div>
    <div class="information_header">
      <p>个人信息</p>
      <p>
        <i class="el-icon-s-flag"></i> By reading we enrich the mind, by
        conversation we polish it.
      </p>
    </div>
    <div class="information_banner" v-loading="loading"
         element-loading-text="拼命加载中"
         element-loading-spinner="el-icon-loading"
         element-loading-background="rgba(0, 0, 0, 0.8)">

      <div class="information_banner_left">
        <div class="banner_left_main" v-if="show">
          <div class="number">
            <i class="el-icon-collection-tag"></i>借阅证编号：{{ this.user.cardNumber }}
          </div>
          <div class="name">
            <i class="iconfont icon-gerenxinxi"></i>借阅证姓名：{{ this.user.cardName }}
          </div>
          <div class="rule">
            <i class="iconfont icon-guizeshezhi"></i>规则编号：{{ this.user.ruleNumber }}
          </div>
          <div class="status">
            <i class="el-icon-refresh"></i>状态：{{ this.user.status === 1 ? "可用" : "禁用" }}
          </div>
        </div>
      </div>

      <div class="information_banner_right">
        <el-button type="primary" class="changePWD" @click="showEditDialog" v-if="show">修改密码</el-button>
      </div>

      <el-dialog
          title="修改密码"
          :visible.sync="editDialogVisible"
          width="40%"
          @close="editDialogClosed"
          class="edit-dialog">
        <el-form
            :model="editForm"
            ref="editFormRef"
            :rules="editFormRules"
            label-width="120px"
        >
          <el-form-item label="新密码" prop="password">
            <el-input v-model="editForm.password" type="password" placeholder="请输入新密码"></el-input>
          </el-form-item>
          <el-form-item label="新密码确认" prop="confirmPassword">
            <el-input v-model="editForm.confirmPassword" type="password" placeholder="请再次输入新密码"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="changePassword">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.editForm.password) {
        callback(new Error('两次输入密码不一致！'));
      } else {
        callback();
      }
    };
    return {
      user: {
        ruleNumber: Number,
        cardNumber: Number,
        status: Number,
        userId: Number,
        cardName: "",
        username: "",
        password: "",
        createTime: "",
        updateTime: "",
      },
      editForm: {
        password: "",
        confirmPassword: "",
      },
      editFormRules: {
        password: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          { min: 6, max: 15, message: "新密码长度在6-15个字符", trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, validator: validatePass2, trigger: "blur" }
        ]
      },
      editDialogVisible: false,
      show: false,
      loading: true
    };
  },
  methods: {
    //让修改公告的对话框可见,并从数据库中回显数据
    showEditDialog() {
      // 让修改公告的对话框可见
      this.editDialogVisible = true;
    },
    //监听修改对话框的关闭，一旦对话框关闭，就重置表单，回显数据
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    async getUserInformaton() {
      // 先从sessionStorage中获取用户id
      const userId = window.sessionStorage.getItem("userId");
      this.loading = true;
      // 发送axios请求，携带用户id，获取个人信息
      const { data: res } = await this.$http.get(
          "user/get_information/" + userId
      );
      if (res.status !== 200) {
        return this.$message.error(res.msg);
      }
      this.$message.success({ message: res.msg, duration: 1000 });
      this.user = res.data;
      this.show = true;
      this.loading = false;
    },
    async changePassword() {
      const { data: res } = await this.$http.post('user/update_password', {
        password: this.editForm.password,
        userId: window.sessionStorage.getItem('userId')
      });
      if (res.status !== 200) {
        return this.$message.error(res.msg);
      }
      this.$message.success(res.msg);
      this.editDialogVisible = false;
      this.$refs.editFormRef.resetFields();
      window.sessionStorage.clear();
      this.$router.push("/login");
    }
  },
  created() {
    this.getUserInformaton();
  },
};
</script>
<style lang="less" scoped>
.information_container {
  position: relative;
  height: 100%;
  background-color: #f7f7f7;
}

.backgroundImg {
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: 1; /* 设置背景图片的 z-index */
  img {
    width: 100%;
    height: 100%;
    object-fit: cover; /* 确保背景图片覆盖 */
    opacity: 0.2; /* 调整透明度，让内容更清晰 */
  }
}
.no-drag {
  user-select: none; /* 防止文字选择 */
  pointer-events: none; /* 防止鼠标事件 */
}

.information_header {
  height: 200px;
  background: rgba(0, 0, 0, 0.5); /* 为头部添加半透明背景 */
  text-align: center;
  color: white;
  padding-top: 50px;

  p:nth-child(1) {
    font-size: 36px;
    font-weight: bold;
  }

  p:nth-child(2) {
    font-size: 18px;
    font-style: italic;
    margin-top: 10px;
  }
}

.information_banner {
  display: flex;
  height: 480px;
  padding: 20px;
  box-sizing: border-box;
  flex-wrap: wrap;
  position: relative; /* 使得子元素的 z-index 生效 */
  .information_banner_left {
    flex: 1;
    padding: 20px;
    background-color: rgba(255, 255, 255, 0.8); /* 设置半透明背景 */
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    z-index: 1; /* 确保按钮在最上层 */
  }
  .information_banner_right {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
    z-index: 2; /* 确保按钮在最上层 */
  }
}

/*.information_banner_left {
  flex: 1;
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.8); !* 设置半透明背景 *!
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}*/

.banner_left_main {
  margin-top: 30px;
  color: #333;
  flex-direction: column; /* 垂直排列 */
  padding: 10px; /* 内边距 */
  font-size: 18px;
  line-height: 1.8;
}

.banner_left_main > div {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  margin-bottom: 15px; /* 每个条目之间的间距 */
}

.banner_left_main i {
  margin-right: 15px; /* 图标与文本之间的间距 */
}

.number, .name, .rule, .status {
  text-align: left; /* 左对齐文本 */
}

/*.information_banner_right {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}*/

.changePWD {
  background-color: #007bff;
  color: white;
  border-radius: 5px;
  padding: 10px 20px;
  font-size: 16px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: background-color 0.3s;
}

.changePWD:hover {
  background-color: #0056b3;
}

.el-dialog {
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
  z-index: 2; /* 确保对话框在最上层 */
}

.el-form-item {
  margin-bottom: 15px;
}

.dialog-footer {
  display: flex;
  justify-content: right;
  margin-top: 20px;
}

.dialog-footer .el-button {
  font-size: 16px;
}

</style>-->

<template>
  <div class="information_container">
    <div class="backgroundImg">
      <img
          src="../../assets/images/tushu.jpg"
          alt="背景图片"
          class="no-drag"
      />
    </div>
    <div class="information_header">
      <p>个人信息</p>
      <p>
        <i class="el-icon-s-flag"></i> By reading we enrich the mind, by
        conversation we polish it.
      </p>
    </div>
    <div class="information_banner" v-loading="loading"
         element-loading-text="拼命加载中"
         element-loading-spinner="el-icon-loading"
         element-loading-background="rgba(0, 0, 0, 0.8)">

      <div class="information_banner_left">
        <div class="banner_left_main" v-if="show">
          <div class="number">
            <i class="el-icon-collection-tag"></i>借阅证编号：{{ this.user.cardNumber }}
          </div>
          <div class="name">
            <i class="iconfont icon-gerenxinxi"></i>借阅证姓名：{{ this.user.cardName }}
          </div>
          <div class="rule">
            <i class="iconfont icon-guizeshezhi"></i>规则编号：{{ this.user.ruleNumber }}
          </div>
          <div class="status">
            <i class="el-icon-refresh"></i>状态：{{ this.user.status === 1 ? "可用" : "禁用" }}
          </div>
        </div>
      </div>

      <div class="information_banner_right">
        <el-button type="primary" class="changePWD" @click="showEditDialog" v-if="show">修改密码</el-button>
        <el-button type="success" class="editInfo" @click="showInfoEditDialog" v-if="show">修改信息</el-button>
      </div>

      <!-- 修改密码弹框 -->
      <el-dialog
          title="修改密码"
          :visible.sync="editDialogVisible"
          width="40%"
          @close="editDialogClosed"
          class="edit-dialog">
        <el-form
            :model="editForm"
            ref="editFormRef"
            :rules="editFormRules"
            label-width="120px"
        >
          <el-form-item label="新密码" prop="password">
            <el-input v-model="editForm.password" type="password" placeholder="请输入新密码"></el-input>
          </el-form-item>
          <el-form-item label="新密码确认" prop="confirmPassword">
            <el-input v-model="editForm.confirmPassword" type="password" placeholder="请再次输入新密码"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="changePassword">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改个人信息弹框 -->
      <el-dialog
          title="修改信息"
          :visible.sync="infoDialogVisible"
          width="50%"
          @close="infoDialogClosed"
          class="info-dialog">
        <el-form
            :model="infoForm"
            ref="infoFormRef"
            label-width="120px"
        >
          <el-form-item label="借阅证姓名" prop="cardName">
            <el-input v-model="infoForm.cardName" placeholder="请输入借阅证姓名"></el-input>
          </el-form-item>

          <el-form-item label="个人头像">
            <el-upload
                class="avatar-uploader"
                action="http://localhost:8889/api/admin/common/upload"
                list-type="picture-card"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                limit="1"
                :headers="headers"
                :on-error="handleAvatarError"
                :file-list="fileList"
            >
              <!--<el-button size="small" type="primary">上传头像</el-button>-->
              <i class="el-icon-plus"></i>
            </el-upload>
            <!--<div v-if="avatarUrl" class="avatar-preview">
              <img :src="avatarUrl" class="avatar" alt="头像预览" />
            </div>-->
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="infoDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateUserInfo">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.editForm.password) {
        callback(new Error('两次输入密码不一致！'));
      } else {
        callback();
      }
    };
    return {
      user: {
        ruleNumber: Number,
        cardNumber: Number,
        status: Number,
        userId: Number,
        cardName: "",
        username: "",
        password: "",
        createTime: "",
        updateTime: "",
        avatar: "",  // 新增头像字段
      },
      editForm: {
        password: "",
        confirmPassword: "",
      },
      infoForm: {
        cardName: "",
        avatar: "", // 保存头像地址
      },
      editFormRules: {
        password: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          { min: 6, max: 15, message: "新密码长度在6-15个字符", trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, validator: validatePass2, trigger: "blur" }
        ]
      },
      editDialogVisible: false,
      infoDialogVisible: false,
      show: false,
      loading: true,
      fileList: [], // 用来保存和图片的回显
      avatarUrl: ""  // 头像预览
    };
  },
  methods: {
    // 让修改密码的对话框可见
    showEditDialog() {
      this.editDialogVisible = true;
    },
    // 监听修改对话框的关闭，一旦对话框关闭，就重置表单
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    // 显示修改个人信息对话框
    async showInfoEditDialog() {
      this.infoForm.cardName = this.user.cardName;
      const userId = window.sessionStorage.getItem("userId");
      // this.avatarUrl = this.user.avatar; // 回显头像
      this.infoDialogVisible = true;
      // 清空上一次上传的图片-->注意随时要更新 fileList 来保证图片上传的状态
      this.fileList = [];
      const { data: res } = await this.$http.get(
          "user/get_information/" + userId
      );
      if (res.status !== 200) {
        return this.$message.error(res.msg);
      }
      this.$message.success({ message: res.msg, duration: 1000 });
      this.user = res.data;
      this.infoForm.avatar = this.user.avatar;
      if (this.infoForm.avatar) {
        //使用fileList数组，添加一个对象，对象中有url属性，将图片路径赋值给url，实现图片回显
        this.fileList = [{ url: this.infoForm.avatar }];
      }
    },
    // 关闭修改个人信息对话框
    infoDialogClosed() {
      this.$refs.infoFormRef.resetFields();
      this.fileList = [];
      // this.avatarUrl = ""; // 清空头像预览
    },
    async getUserInformaton() {
      const userId = window.sessionStorage.getItem("userId");
      this.loading = true;
      const { data: res } = await this.$http.get(
          "user/get_information/" + userId
      );
      if (res.status !== 200) {
        return this.$message.error(res.msg);
      }
      this.$message.success({ message: res.msg, duration: 1000 });
      this.user = res.data;
      this.show = true;
      this.loading = false;
    },
    // 上传头像成功的回调
    handleAvatarSuccess(response, file) {
      this.avatarUrl = response.msg;  // 假设返回值包含文件URL
    },
    // 上传前进行检查
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isGIF = file.type === 'image/gif';
      if (!isJPG && !isPNG && !isGIF) {
        this.$message.error('上传头像图片只能是 JPG、PNG 或 GIF 格式!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('头像图片大小不能超过 2MB!');
      }
      return isJPG || isPNG || isGIF && isLt2M;
    },
    handleAvatarError(err) {
      this.$message.error('上传失败，请重试');
    },
    // 提交修改的个人信息
    async updateUserInfo() {
      const { data: res } = await this.$http.post('user/update_info', {
        cardName: this.infoForm.cardName,
        avatar: this.avatarUrl,
        userId: window.sessionStorage.getItem('userId')
      });
      if (res.status !== 200) {
        return this.$message.error(res.msg);
      }
      this.$message.success(res.msg);
      this.infoDialogVisible = false;
      this.user.cardName = this.infoForm.cardName;
      this.user.avatar = this.avatarUrl;  // 更新头像和姓名
      // 更新成功后刷新页面-->重新加载页面回显用户头像
      location.reload();
    },
    // 修改密码
    async changePassword() {
      const { data: res } = await this.$http.post('user/change_password', {
        password: this.editForm.password,
        userId: window.sessionStorage.getItem('userId')
      });
      if (res.status !== 200) {
        return this.$message.error(res.msg);
      }
      this.$message.success(res.msg);
      this.editDialogVisible = false;
    }
  },
  mounted() {
    this.getUserInformaton();
  },
  computed: {
    headers() {
      return {
        "Authorization": "Bearer " + window.sessionStorage.getItem('token')
      };
    }
  }
};
</script>

<style scoped>

.information_container {
  position: relative;
  height: 100%;
  background-color: #f7f7f7;
}

.backgroundImg {
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: 1; /* 设置背景图片的 z-index */
  img {
    width: 100%;
    height: 100%;
    object-fit: cover; /* 确保背景图片覆盖 */
    opacity: 0.2; /* 调整透明度，让内容更清晰 */
  }
}
.no-drag {
  user-select: none; /* 防止文字选择 */
  pointer-events: none; /* 防止鼠标事件 */
}

.information_header {
  height: 200px;
  background: rgba(0, 0, 0, 0.5); /* 为头部添加半透明背景 */
  text-align: center;
  color: white;
  padding-top: 50px;

  p:nth-child(1) {
    font-size: 36px;
    font-weight: bold;
  }

  p:nth-child(2) {
    font-size: 18px;
    font-style: italic;
    margin-top: 10px;
  }
}

.information_banner {
  display: flex;
  height: 480px;
  padding: 20px;
  box-sizing: border-box;
  flex-wrap: wrap;
  position: relative; /* 使得子元素的 z-index 生效 */
  .information_banner_left {
    flex: 1;
    padding: 20px;
    background-color: rgba(255, 255, 255, 0.8); /* 设置半透明背景 */
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    z-index: 1; /* 确保按钮在最上层 */
  }
  .information_banner_right {
    flex: 1;
    display: flex;
    /*flex-direction: column;
    gap: 20px;*/
    justify-content: center;
    align-items: center;
    padding: 20px;
    z-index: 2; /* 确保按钮在最上层 */
  }
}

/*.information_banner_left {
  flex: 1;
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.8); !* 设置半透明背景 *!
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}*/

.banner_left_main {
  margin-top: 30px;
  color: #333;
  flex-direction: column; /* 垂直排列 */
  padding: 10px; /* 内边距 */
  font-size: 18px;
  line-height: 1.8;
}

.banner_left_main > div {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  margin-bottom: 15px; /* 每个条目之间的间距 */
}

.banner_left_main i {
  margin-right: 15px; /* 图标与文本之间的间距 */
}

.number, .name, .rule, .status {
  text-align: left; /* 左对齐文本 */
}

/*.information_banner_right {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}*/

.changePWD {
  background-color: #007bff;
  color: white;
  border-radius: 5px;
  padding: 10px 20px;
  font-size: 16px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: background-color 0.3s;
}

.changePWD:hover {
  background-color: #0056b3;
}
.editInfo {
  color: white;
  border-radius: 5px;
  padding: 10px 20px;
  font-size: 16px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: background-color 0.3s;
}

.editInfo:hover {
  background-color: darkgreen;
}
.el-dialog {
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
  z-index: 2; /* 确保对话框在最上层 */
}

.el-form-item {
  margin-bottom: 15px;
}

.dialog-footer {
  display: flex;
  justify-content: right;
  margin-top: 20px;
}

.dialog-footer .el-button {
  font-size: 16px;
}
</style>

